Skip to content

Latest commit

 

History

History

0567-Permutation in String

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 

567. Permutation in String

Given two strings s1 and s2, return true if s2 contains the permutation of s1.

In other words, one of s1's permutations is the substring of s2.

Example 1:

Input: s1 = "ab", s2 = "eidbaooo" Output: true Explanation: s2 contains one permutation of s1 ("ba"). 

Example 2:

Input: s1 = "ab", s2 = "eidboaoo" Output: false 

Constraints:

  • 1 <= s1.length, s2.length <= 104
  • s1 and s2 consist of lowercase English letters.

Solutions (Ruby)

1. Sliding Window

# @param {String} s1# @param {String} s2# @return {Boolean}defcheck_inclusion(s1,s2)returnfalseifs1.size > s2.sizecount1=[0] * 26count2=[0] * 26(0...s1.size).eachdo |i| count1[s1[i].ord - 97] += 1count2[s2[i].ord - 97] += 1end(0..s2.size - s1.size).eachdo |i| returntrueifcount1 == count2ifi + s1.size < s2.sizecount2[s2[i].ord - 97] -= 1count2[s2[i + s1.size].ord - 97] += 1endendfalseend

Solutions (Rust)

1. Sliding Window

implSolution{pubfncheck_inclusion(s1:String,s2:String) -> bool{if s1.len() > s2.len(){returnfalse;}let s1 = s1.as_bytes();let s2 = s2.as_bytes();letmut count1 = [0;26];letmut count2 = [0;26];for i in0..s1.len(){ count1[(s1[i] - b'a')asusize] += 1; count2[(s2[i] - b'a')asusize] += 1;}for i in0..=s2.len() - s1.len(){if count1 == count2 {returntrue;}if i + s1.len() < s2.len(){ count2[(s2[i] - b'a')asusize] -= 1; count2[(s2[i + s1.len()] - b'a')asusize] += 1;}}false}}
close